<template>
  <div class="mt-3 ">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :lg="18">
        <div class="app_card  pt-2  pb-5">
          <div class="text-16 my-4">{{bildingDto?.name}}&emsp;</div>
          <div style="height:calc(100vh - 360px);overflow-y: scroll;">
            <el-row :gutter="15" class="w100 mt-3">
              <el-col class="mb-3" :xs="12" :sm="12" :lg="radioIcon == '1' ? { span: bigCol } : { span: smallCol }" v-for="(item, index) in dataOfTable" :key="index" @click="handelClick(item)">
                <el-card shadow="never" :class="{
                'online':item.online=='1',//在线
                'offline':item.online=='0',//离线
                'fault':item.repairStatus=='1',//故障
                'bigHeight':radioIcon == '1',
                'smallHeight':radioIcon != '1',
                'checkBorder':item.isCheck
                }">
                  <template #header>
                    <div class="card-header" :class="radioIcon == '1' ? 'text-20' : 'text-14'">
                      <div class="text-truncate">
                        <span class="tag"></span>
                        <span :class="radioIcon == '1' ? 'ml-3' : 'ml-1'">
                          {{item.floor}}{{item.name}}-{{item.online=='1'?'在线':'离线'}}
                        </span>
                        <span class="text-12" v-if="item.online=='1'">
                          （{{item.repairStatus == 1 ? "已报修" : "未报修"}}）
                        </span>
                      </div>
                      <el-button link @click="onLink(item)" @click.stop="onStop()" class="text-white-50 text-14">详情</el-button>
                    </div>
                  </template>
                  <div class="position-relative">
                    <template v-for="(items,index) in item.equipments">
                      <div class="position-relative float-start w-25 t-c ptb-2" v-if="items.type!='0'">
                        <el-tooltip :content="items.equipmentName">
                          <img :src="`./images/equi/${getPng(items)}.png`" alt :class="radioIcon == '1' ? 'img30' : 'img20'" />
                        </el-tooltip>
                      </div>
                    </template>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
          <div class="mt-2">
            <el-pagination background v-model:currentPage="queryParam.page" v-model:page-size="queryParam.limit" :page-sizes="paginationOption.pageSizes" :background="false" :layout="paginationOption.layout" :total="paginationOption.totalCount" @size-change="handleChangeSize" @current-change="handleChangeCurrent" />
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :lg="6">
        <div class="app_card  pt-2  pb-5">
          <div class="text-16 my-4">控制面板</div>
          <div style="height:calc(100vh - 330px);overflow-y: scroll;">
            <RoomJoin ref="roomJoinRef" @roomFetch="roomFetch" :roomData="roomData"></RoomJoin>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
/**
 * 面板控制
 */
import { ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { ElLoading } from 'element-plus'
import { getNewObj } from '@/utils/EsCommon';
import Pagination from '@/components/pagination/index.vue';
import RoomJoin from './RoomJoin.vue';

import { useWebSocketStore } from '@/stores/useWebSocketStore';
const socketStore = useWebSocketStore();




// 监听socketStore中值的变化
const subscribe = socketStore.$subscribe((mutation, state) => {
  // console.error('mutation=======', mutation)
  // console.error('state=======', state)
  if (state.socketMessage) {
    try {
      //模拟数据
      //       let socketMessage = `{
      //     "id": 108,
      //     "online": 1,
      //     "list": [
      //         {
      //             "joinNum": 3,
      //             "status": "1"
      //         }
      //     ],
      //     "event": "",
      //     "data": {
      //         "remoteRoom": 0,
      //         "localUser": ""
      //     }
      // }`
      //       const message = JSON.parse(socketMessage)
      const message = JSON.parse(state.socketMessage)
      for (var i = 0; i < dataOfTable.value.length; i++) {
        if (dataOfTable.value[i].id == message.id) {
          dataOfTable.value[i].online = message.online;
          if (message.id == roomData.value?.id) {
            roomJoinRef.value.getRoomJoinnum(message.id, false);
          }

          for (var x = 0; x < dataOfTable.value[i].equipments.length; x++) {
            for (var j = 0; j < message.list.length; j++) {
              if (
                message.list[j].joinNum ==
                dataOfTable.value[i].equipments[x].joinNum
              ) {
                dataOfTable.value[i].equipments[x].status = message.list[j].status;
              }
            }
          }
        }
      }

    } catch (error) {
      console.log(error)

    }
  }
}, { detached: false })  //第二个参数options对象，是各种配置参数




// ======================================================
//                      变量声明
// ======================================================
const emit = defineEmits(['goRoom']);

const props = defineProps({
  bildingDto: {
    type: Object,
    default() {
      return {}
    }
  }
})

// 组件引用
const roomJoinRef = ref(null);
const paginationRef = ref(null);
// 表格数据
const loading = ref(false);
const dataOfTable = ref([]);

// 表格查询参数
const queryForm = ref({
  floorId: "",
  buildingId: "",
  radio_floor: "",
})

// 表格查询参数
const queryParam = ref({
  sort: "Id",
  order: "asc",
  page: 1,
  limit: 20,
})
const selectAll = ref(false);
//1大图 2小图
const radioIcon = ref('1');
const bigCol = ref(8);
const smallCol = ref(4);
// 表格多选数据
const roomData = ref({});

// 点击详情
const onLink = (row) => {
  emit('goRoom', row)
}

const handelClick = (item) => {
  if (!selectAll.value) {
    dataOfTable.value.forEach(element => {
      if (element.id != item.id) {
        element.isCheck = false
      }
    });
    item.isCheck = !item.isCheck
    if (item.isCheck) {
      roomData.value = getNewObj(item)
      roomJoinRef.value.getRoomJoinnum(item.id);
    }
  }
}
// ======================================================
//                      处理事件
// ======================================================
// 阻止冒泡
const onStop = () => {
}
// 获取设备图片
const getPng = (items) => {
  let _index = ''
  switch (items.status) {
    case "0":
      _index = `${items.type}`
      break;
    case "-1":
      _index = `${items.type}-1`
      break;
    case "1":
      _index = `${items.type}-2`
      break;
    default:
      _index = `${items.type}`
      break;
  }
  return _index
}

// ======================================================
//                      处理事件
// ======================================================
const onRefresh = (query) => {
  console.error('onRefresh====', query)
  queryForm.value.buildingId = ""
  queryForm.value.floorId = ""

  let { radio_icon = "", buildingId = "", radio_floor = "", floorId = "" } = query
  if (radio_icon) {
    radioIcon.value = radio_icon
  }
  if (buildingId) {
    queryForm.value.buildingId = buildingId
  }
  if (floorId) {
    queryForm.value.floorId = floorId
  }
  if (radio_floor) {
    queryForm.value.radio_floor = radio_floor
  }
  roomFetch();
}
const roomFetch = () => {
  if (radioIcon.value == '2') {//小图
    queryParam.value.limit = 20
  } else if (radioIcon.value == '1') {//大图
    queryParam.value.limit = 15
  }
  roomData.value = {}
  queryParam.value.page = 1;
  paginationOption.value.totalCount = 0
  loadData()
}


// 分页栏配置数据
const paginationOption = ref({
  layout: 'total, sizes, prev, pager, next, jumper',
  pageSizes: [12, 15, 20, 25, 30],
  totalCount: 0,
})


// 处理分页尺寸
const handleChangeSize = (val) => {
  queryParam.value.page = 1;
  queryParam.value.limit = val;
  loadData()
}

// 处理页码
const handleChangeCurrent = (val) => {
  queryParam.value.page = val;
  loadData()
}
const loadData = (query) => {
  dataOfTable.value = []
  let _queryParam = queryParam.value
  _queryParam.query = ''


  let url = ApiUrls.roomSearch
  console.log(queryForm.value.radio_floor)
  if (queryForm.value.radio_floor == '-2') {//上课中
    url = ApiUrls.roomInclass
  } else if (queryForm.value.radio_floor == '-3') {//故障
    url = ApiUrls.roomFault
  } else if (queryForm.value.radio_floor == '-4') {//故障
    url = ApiUrls.roomFree
  }


  if (queryForm.value.buildingId) {
    _queryParam.query = "buildingId=" + queryForm.value.buildingId;
  }
  if (queryForm.value.floorId) {
    // url = ApiUrls.roomSearch
    _queryParam.query += ",floorId=" + queryForm.value.floorId;
  }
  _queryParam.offset = (_queryParam.page - 1) * _queryParam.limit || 0;
  loading.value = true

  const loadingInstance = ElLoading.service({ text: '查询中...' })
  EsAjax.post(url, _queryParam).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }
    let { list, totalCount } = res.data.data
    if (list && list.length) {
      list.forEach(element => {
        element.isCheck = false
      });
    }
    dataOfTable.value = list;
    paginationOption.value.totalCount = totalCount
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loadingInstance.close()
    loading.value = false
  })
}

defineExpose({
  loadData,
  onRefresh
})

</script>
<style lang="less" scoped>
:deep(.el-button--small) {
  padding: 5px 6px;
}
:deep(.el-button--primary.is-plain) {
  border: none;
  color: #0db895;
  background: rgba(13, 184, 149, 0.1);
}
.img30 {
  width: 30px;
}
.img20 {
  width: 20px;
}
.tag {
  width: 40px;
  height: 40px;
  display: inline-block;
  position: absolute;
  left: 0px;
  top: 5px;
}
.typeIcon {
  width: 33px;
  height: 33px;
  display: inline-block;
  &.sm {
    width: 15px !important;
    height: 15px !important;
  }
}
:deep(.el-card__header) {
  padding-left: 20px;
  position: relative;
}
.smallHeight {
  height: 190px;
  box-sizing: border-box;
  border-radius: 5px;
  .typeIcon {
    width: 22px;
    height: 22px;
  }
  .tag {
    width: 30px;
    height: 30px;
    top: 9px;
  }
}
.bigHeight {
  height: 250px;
  box-sizing: border-box;
  border-radius: 5px;
  :deep(.el-card__header) {
    padding: 20px;
  }
  .tag {
    top: 13px;
  }
}
.checkBorder {
  border: 2px solid #0db895 !important;
}
.online {
  .tag {
    background: url("@/assets/img/room/online-tag.png") no-repeat;
    background-size: 100%;
  }
  :deep(.el-card__header) {
    background: linear-gradient(
      90deg,
      rgba(15, 209, 169, 6) 0%,
      rgba(15, 209, 169, 0) 100%
    );
    border-bottom: 4px solid;
    border-image-source: linear-gradient(
      90deg,
      #0fd1a9 0%,
      rgba(15, 209, 169, 0) 100%
    );
    border-image-slice: 1;
  }
}

.fault {
  .tag {
    background: url("@/assets/img/room/fault-tag.png") no-repeat;
    background-size: 100%;
  }
  :deep(.el-card__header) {
    background: linear-gradient(
      90deg,
      rgba(255, 187, 0, 0.6) 0%,
      rgba(255, 187, 0, 0) 100%
    );
    border-bottom: 4px solid;
    border-image-source: linear-gradient(
      90deg,
      #ffbb00 0%,
      rgba(255, 187, 0, 0) 100%
    );
    border-image-slice: 1;
  }
}
.offline {
  .tag {
    background: url("@/assets/img/room/offline-tag.png") no-repeat;
    background-size: 100%;
  }
  :deep(.el-card__header) {
    background: linear-gradient(
      90deg,
      rgba(255, 255, 255, 0.2) 0%,
      rgba(255, 255, 255, 0) 100%
    ) !important;
    border-bottom: 4px solid;
    border-image-source: linear-gradient(
      90deg,
      rgba(255, 255, 255, 0.2) 0%,
      rgba(255, 255, 255, 0) 100%
    ) !important;
    border-image-slice: 1;
  }
}

:deep(.el-radio-button__inner) {
  background: transparent;
  color: #fff;
}
:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  color: #0db895;
  background: rgba(13, 184, 149, 0.1);
  border-color: #0db895;
}
.detail {
  width: 40px;
}
</style>
  
